package com.mjt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.mjt.admin.pojo.Role;
import com.mjt.admin.pojo.User;
import com.mjt.admin.pojo.UserRole;
import com.mjt.admin.service.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create 2021-10-29 14:51
 */
@Service
public class RbacServiceImpl implements IRbacService {

    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private IMenuService menuService;
    @Resource
    private IRoleMenuService roleMenuService;




    /**
     * @description 根据当前用户名查询角色名称
     * @author 莫某人
     * @date 14:52 2021/10/29
 * @param userName
     * @return {@link List< String>}
     **/

    @Override
    public List<String> selectRoleNameByUserName(String userName) {

        //查询用户
        User user = userService.findUserByUsername(userName);
        //根据用户id查询角色id
        List<Integer> roleids = userRoleService
                .list(new QueryWrapper<UserRole>().
                        eq("user_id", user.getId()))
                .stream().map(ur -> ur.getRoleId()).collect(Collectors.toList());

        //查询角色名称
        List<String> roleNames = roleService.listByIds(roleids).
                stream().map(r -> r.getName()).collect(Collectors.toList());
        return roleNames;
    }

    @Override
    public List<String> selectAuthoritiesByRoleName(List<String> roleNames) {

        //List<Integer> roleIdList = new ArrayList<>();
        ////查询角色id
        //for (String roleName : roleNames) {
        //    Integer roleId = roleService.getOne(new QueryWrapper<Role>().eq("name", roleName)).getId();
        //    roleIdList.add(roleId);
        //}
        ////根据角色id集合查询菜单id
        //List<Integer> menuIds = roleMenuService.listByIds(roleIdList).stream().map(rm -> rm.getMenuId()).collect(Collectors.toList());
        ////根据菜单id查询菜单名称
        //List<String> menuNames = menuService.listByIds(menuIds).stream().map(m -> m.getName()).collect(Collectors.toList());

        return roleMenuService.selectAuthoritiesByRoleName(roleNames);



    }
}
